<?php
declare(strict_types=1);

namespace App\Console\Commands\Tasks;

use App\Enums\StreamerEnum;
use App\Repositories\Streamer\StreamerApplyRepository;
use App\Repositories\Streamer\StreamerRepository;
use App\Repositories\Streamer\StreamerTaskRecordRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class StreamerChatReplyExpCommand extends Command
{
    //命令名
    protected $signature = 'task:streamer_chat_reply_exp';

    //命令描述
    protected $description = 'streamer chat reply';

    public function getSignature()
    {
        return $this->signature;
    }

    public function __construct()
    {
        parent::__construct();
    }

    //业务处理
    public function handle()
    {
        $userIds =  StreamerApplyRepository::getInstance()->streamers();
        // 昨天时间戳
        $start = Carbon::now()->addDays(-1)->startOfDay()->timestamp;
        $end = Carbon::now()->addDays(-1)->startOfDay()->timestamp;
        foreach ($userIds as $userId) {
            // 收到用户的消息
            $sends = app("model_chat")->newQuery()
                ->where("user_id_to", $userId)
                ->where("type", 2)
                ->whereBetween("add_time", [$start, $end])
                ->groupBy(["user_id"])
                ->select(["user_id", DB::raw("min(add_time) as time")])
                ->get();

            // 获取主播回复的最小时间
            $total = $sends->count();
            $totalSecond = 0;

            foreach ($sends as $send){
                $reply = app("model_chat")->newQuery()
                    ->where("user_id_to", $send->user_id)
                    ->where("type", 2)
                    ->where("user_id", $userId)
                    ->where("add_time", ">=", $send->time)
                    ->whereBetween("add_time", [$start, $end])
                    ->select(["user_id", "add_time"])
                    ->first();
                if($reply){
                   $totalSecond += $reply->add_time - $send->time;
                }
            }

            $avgSecond = floor($totalSecond / $total);
            switch ($avgSecond){
                case 1 <= $avgSecond && $avgSecond >= 20:
                    $exp = 50;
                    break;
                case 21 <= $avgSecond && $avgSecond >= 40:
                    $exp = 30;
                    break;
                case 41 <= $avgSecond && $avgSecond >= 60:
                    $exp = 10;
                    break;
                default:
                    $exp = 0;
                    break;
            }

            if($exp > 0){
                StreamerRepository::getInstance()->incStreamerScore($userId, $exp, StreamerEnum::EXP_TYPE_CHAT_REPLY, 0);
            }
        }
    }

}